/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.auth.shiro.handlers;


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.zfes.snowy.auth.shiro.exceptions.IncorrectCaptchaException;
import org.zfes.snowy.core.consts.FrameConst;
import org.zfes.snowy.core.data.JSONMSG;
import org.zfes.snowy.core.util.ZWebUtil;

public class SimpleAuthecFailureHandler extends AbstractAuthecHandler {
	
	private String defaultAuthecFailureUrl="login.html";
	
	private boolean authecFailureForwardToDestination = false;
	
	public void onAuthenticationFailure(HttpServletRequest request,HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {
		String mesage="";
		if(exception instanceof UnknownAccountException||exception instanceof IncorrectCredentialsException){
			mesage="用户名或密码错误";
		}else if(exception instanceof LockedAccountException){
			mesage="用户已经锁定";
		}else if(exception instanceof ExcessiveAttemptsException){
			mesage="重复登录次数过多";
		}else if(exception instanceof IncorrectCaptchaException){
			mesage="验证码错误";
		}else{
			mesage="认证未通过";
		}
		if(ZWebUtil.isAjax(request)){
			ZWebUtil.respJSON(response, JSONMSG.newMSG(FrameConst.SC.SC_401, "认证失败【"+mesage+"】"));
			return;
		}
		if(authecFailureForwardToDestination){
			saveRequestAndForward( request,  response, getDefaultAuthecFailureUrl()) ;
			return;
		}else{
			saveRequestAndRedirect( request,  response, getDefaultAuthecFailureUrl());
			return;
		}
	}
	public void onAuthenticationFailure(HttpServletRequest request,HttpServletResponse response, String mesage)
			throws IOException, ServletException {
		if(ZWebUtil.isAjax(request)){
			ZWebUtil.respJSON(response, JSONMSG.newMSG(FrameConst.SC.SC_401, "认证失败【"+mesage+"】"));
			return;
		}
		if(authecFailureForwardToDestination){
			saveRequestAndForward( request,  response, getDefaultAuthecFailureUrl()) ;
			return;
		}else{
			saveRequestAndRedirect( request,  response, getDefaultAuthecFailureUrl());
			return;
		}
	}

	public String getDefaultAuthecFailureUrl() {
		return defaultAuthecFailureUrl;
	}


	public void setDefaultAuthecFailureUrl(String defaultAuthecFailureUrl) {
		this.defaultAuthecFailureUrl = defaultAuthecFailureUrl;
	}


	public boolean isAuthecFailureForwardToDestination() {
		return authecFailureForwardToDestination;
	}


	public void setAuthecFailureForwardToDestination(boolean authecFailureForwardToDestination) {
		this.authecFailureForwardToDestination = authecFailureForwardToDestination;
	}


	
}
